﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using Mehdime.Entity;
using WikeSoft.Core;
using WikeSoft.Core.Extension;
using WikeSoft.Data;
using WikeSoft.Data.Models;
using WikeSoft.Data.Models.Sys;
using WikeSoft.Enterprise.Entities;
using WikeSoft.Enterprise.Enum;
using WikeSoft.Enterprise.Interfaces.Sys;
using WikeSoft.Enterprise.Models;
using WikeSoft.Enterprise.Models.Filters.Sys;
using WikeSoft.Enterprise.Models.Sys;

namespace WikeSoft.Enterprise.AppServices.Sys
{
    /// <summary>
    /// 角色服务
    /// </summary>
    public class RoleService : IRoleService
    {
        private readonly IMapper _mapper;
        private readonly IDbContextScopeFactory _dbContextScopeFactory;
        public RoleService(IMapper mapper, IDbContextScopeFactory dbContextScopeFactory)
        {
            _mapper = mapper;
            _dbContextScopeFactory = dbContextScopeFactory;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Add(RoleAddModel model)
        {
            using (var scope = _dbContextScopeFactory.Create())
            {
              
                var db = scope.DbContexts.Get<WikeDbContext>();
                var entity = _mapper.Map<RoleAddModel, SysRole>(model);
                entity.CreateDate = DateTime.Now;
                db.SysRoles.Add(entity);
                return scope.SaveChanges() > 0;
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Edit(RoleEditModel model)
        {
            using (var scope = _dbContextScopeFactory.Create())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var userEntity = db.SysRoles.Load(model.Id);
                _mapper.Map(model, userEntity);
                scope.SaveChanges() ;
            }
            return true;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        public RoleEditModel Find(string id)
        {
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var entity = db.SysRoles.Load(id);
                return _mapper.Map<SysRole, RoleEditModel>(entity);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids">id集合</param>
        /// <returns></returns>
        public bool Delete(IList<string> ids)
        {
            using (var scope = _dbContextScopeFactory.Create())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var list = db.SysRoles.Where(x => ids.Contains(x.Id)).ToList();
                list.ForEach(c =>
                {
                    c.IsDelete = true;
                });  
                return scope.SaveChanges() > 0;
            }
        }

        /// <summary>
        /// 验证角色名是否重复
        /// </summary>
        /// <param name="roleId">角色id，可以为空，为空表示添加</param>
        /// <param name="roleName">角色名称</param>
        /// <returns></returns>
        public bool IsExists(string roleId, string roleName)
        {
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var query = db.SysRoles.Where(x => x.RoleName == roleName);
                //如果是编辑，则需要把自己排除
                if (roleId.IsNotBlank())
                {
                    query = query.Where(x => x.Id != roleId);
                }
                return query.Any();
            }
        }

        /// <summary>
        /// 设置指定的角色能够访问的页面
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <param name="pageIds">页面ID集合</param>
        /// <returns></returns>
        public bool SetRights(string roleId, IList<string> pageIds)
        {
            using (var scope = _dbContextScopeFactory.Create())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var role = db.SysRoles.Load(roleId);
                var currentPages = role.SysPages.ToList();
                if (pageIds.AnyOne())
                {
                    //提取新增的页面权限
                    var addedPageIds = pageIds.Where(x => currentPages.All(p => p.Id != x)).ToList();
                    //提取删除的页面权限
                    var deletedPages = currentPages.Where(x => !pageIds.Contains(x.Id)).ToList();
                    if (addedPageIds.AnyOne())
                    {
                        var addedPages = db.SysPages.Where(x => addedPageIds.Contains(x.Id)).ToList();
                        role.SysPages.AddRange(addedPages);
                    }
                    role.SysPages.RemoveRange(deletedPages);
                }
                else
                {
                    //表示删除所有的权限
                    if (role.SysPages.Any())
                    {
                        role.SysPages = null;
                    }  
                }
                scope.SaveChanges();
                return true;
            }
        }

        /// <summary>
        /// 分页查询信息
        /// </summary>
        /// <param name="filters"></param>
        /// <returns></returns>
        public PagedResult<RoleModel> Query(RoleFilter filters)
        {
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var query = db.SysRoles.Where(x => x.IsDelete==false);
                if (filters.keywords.IsNotBlank())
                {
                    query = query.Where(x => x.RoleName.Contains(filters.keywords) ||
                                             x.Remark.Contains(filters.keywords));
                }
               
                var data = query.OrderByCustom(filters.sidx, filters.sord)
                    .Select(item => new RoleModel
                    {
                        Id = item.Id,
                        RoleName = item.RoleName,
                        Remark = item.Remark,
                        CreateDate = item.CreateDate.Value,
                        //TrueNames = string.Join(";", item.SysUsers.AsEnumerable().Select(p => p.TrueName).ToArray())
                    }).Paging(filters.page, filters.rows);

                foreach (var row in data.rows)
                {
                    var r = db.SysRoles.Find(row.Id);
                    if (r != null)
                    {
                        var users = r.SysUsers.ToList();
                        row.TrueNames = users.Select(c => c.TrueName).Join(",");
                    }
                }

                return data;
            }
        }

      
        /// <summary>
        /// 获取所有的角色
        /// </summary>
        /// <param name="id">用户/页面ID</param>
        /// <param name="type">角色类型</param>
        /// <returns></returns>
        public List<RoleModel> GetAllRoles(string id, RoleType type)
        {
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var roles = db.SysRoles.Where(x=>x.IsDelete==false).Select(x => new RoleModel
                {
                    Id = x.Id,
                    RoleName = x.RoleName
                }).ToList();
                if (id.IsNotBlank())
                {
                    ICollection<SysRole> ownRoles = new List<SysRole>();
                    if (type == RoleType.User)
                    {
                        var user = db.SysUsers.Load(id);
                        ownRoles = user.SysRoles;
                    }else if (type == RoleType.Page)
                    {
                        var page = db.SysPages.Load(id);
                        ownRoles = page.SysRoles;
                    }
                    roles.ForEach(x => x.Checked = ownRoles.Any(r => r.Id == x.Id));
                }
                return roles;
            }
        }

        /// <summary>
        /// 获取所有的ztree模型树
        /// </summary>
        /// <returns></returns>
        public List<ZTreeModel> GetRoleTrees()
        {
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var list = db.SysRoles.Where(c=>c.IsDelete==false).ToList();
                var result = _mapper.Map<List<SysRole>, List<ZTreeModel>>(list);
                result.ForEach(t => t.open = true);
                return result;
            }
        }

        /// <summary>
        /// 根据角色ID获取角色的权限
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public List<string> GetRoleRights(string roleId)
        {
            using (var scope = _dbContextScopeFactory.CreateReadOnly())
            {
                var db = scope.DbContexts.Get<WikeDbContext>();
                var role = db.SysRoles.Load(roleId);
                return role.SysPages.Where(x=>x.IsDelete==false).Select(x => x.Id).ToList();
            }
        }
    }
}
